<?php
/**
 * brand.php
 *
 * Created on 2014-12-26
 * Create by LDD
 */
namespace haibao\www\data;

use haibao\www\model\data\BrandProperty;

use \haibao\www\model\filter\Brand as BrandFilter;
use \haibao\www\model\filter\BrandType as BrandTypeFilter;
use \haibao\www\model\filter\BrandProperty as BrandPropertyFilter;

class Brand extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\www\model\data\Brand');
	}

	/**
	 * @parma \haibao\cms\model\filter\Brand $brandFilter;
	 */
	public function getAll($brandFilter){
        return parent::getAll($brandFilter);
	}
	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function add($model){
		
		$this->beginTranscation();
		try{
			parent::add($model);
 			$this->addBrandProperty($model);
			$this->addBrandType($model);
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)){
			$oldId = $this->addOldBrandLibrary($model);
			$this->addDataMigrationMap($model,$oldId);
		}
	}
	
	/**
	 * 其他模块调用添加品牌
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function addBrandForOther($model,$syncOld = true){
	
		$this->beginTranscation();
		try{
			parent::add($model);
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
        if(\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)){
            if($syncOld){
			    $oldId = $this->addOldBrandLibrary($model);
                $this->addDataMigrationMap($model,$oldId);
            }
        }
        return  $model->Id;
    }
	/**
	 * 通过品牌Id查找品牌
	 */
	public function getBrandById($brandIds,$isLock = false){
		$isOneModel = true;
		if(is_array($brandIds)){
			$isOneModel = false;
		} else {
			$brandIds = array($brandIds);
		}
		$brandFilter = new BrandFilter();
		$brandTypeFilter = new BrandTypeFilter();
		$brandPropertyFilter = new BrandPropertyFilter();
		$brandFilter->select(array(
				BrandFilter::CONDITION_FIELD_NAEM_ISHOT,
				BrandFilter::CONDITION_FIELD_NAEM_ISRECOMMEND,
				BrandFilter::CONDITION_FIELD_NAEM_STORY,
				BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_TIME,
				BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_NATION,
				BrandFilter::CONDITION_FIELD_NAME_IMGID,
				BrandFilter::CONDITION_FIELD_NAME_BRANDREGION,
				BrandFilter::CONDITION_FIELD_NAME_BUYTYPE,
				BrandFilter::CONDITION_FIELD_NAME_CURDESIGNER,
				BrandFilter::CONDITION_FIELD_NAME_DESCRIPTION,
				BrandFilter::CONDITION_FIELD_NAME_FOUNDER,
				BrandFilter::CONDITION_FIELD_NAME_ID,
				BrandFilter::CONDITION_FIELD_NAME_TAG_ID,
				BrandFilter::CONDITION_FIELD_NAME_NAMECN,
				BrandFilter::CONDITION_FIELD_NAME_NAMEEN,
				));
		$brandPropertyFilter->select(array(
				BrandPropertyFilter::CONDITION_FIELD_NAME_PROPERTY,
				BrandPropertyFilter::CONDITION_FIELD_NAME_BRAND_ID
				));
		$brandTypeFilter->select(array(
				BrandTypeFilter::CONDITION_FIELD_NAME_BRAND_ID,
				BrandTypeFilter::CONDITION_FIELD_NAME_TYPE
				));
		$brandFilter->leftJoin($brandPropertyFilter,null,BrandFilter::CONDITION_FIELD_NAME_ID,BrandPropertyFilter::CONDITION_FIELD_NAME_BRAND_ID,BrandFilter::CONDITION_FIELD_NAME_BRAND_PROPERTY);
		$brandFilter->leftJoin($brandTypeFilter,null,BrandFilter::CONDITION_FIELD_NAME_ID,BrandTypeFilter::CONDITION_FIELD_NAME_BRAND_ID,BrandFilter::CONDITION_FIELD_NAME_BRAND_TYPE);
		
		$brandFilter->where(BrandFilter::CONDITION_FIELD_NAME_ID, \haibao\frame\data\query\Condition::CONDITION_IN, $brandIds);
		if(!$isLock){
			$brandFilter->where(BrandFilter::CONDITION_FIELD_NAME_STATUS, \haibao\frame\data\query\Condition::CONDITION_EQUAL, \haibao\cms\model\data\Brand::STATUS_ENABLE);
		}
		$brandModel = null;
		if($isOneModel){
			$brandModel = $this->getOne($brandFilter);
		} else {
			$brandModel = $this->getAll($brandFilter);
		}
		return $brandModel;
	}
	/**
	 * 创建设计师的空间
	 */
	public function createDesignerSpace($brandModel){
		parent::add($brandModel);
		if(\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)){
			$oldId = $this->createOldDesignerSpace();
			$this->addDataMigrationMap($brandModel,$oldId);
		}
	}
	/**
	 * 通过tagId删除品牌
	 */
	public function deleteBrandByTagId($tagId,$filter){
		parent::update(array(
				\haibao\cms\model\filter\Brand::CONDITION_FIELD_NAME_STATUS=>\haibao\cms\model\data\Brand::STATUS_DISABLE),
				 $filter);
		if(\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)){
			$this->deleteOldBrandLibraryByTagId($tagId);
		}
	}
	private function deleteOldBrandLibraryByTagId($tagId){
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$sql ="update `library_brand` set status =0 where tag_id= %s";
		$this->query($sql,array($tagId));
	}
	/**
	 * 通过tagId删除设计师空间
	 */
	public function deletecDesignerSpaceByTagId($tagId,$filter){
		parent::remove($filter);
		if(\haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD)){
			$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$sql ="delete from `library_brand` where tag_id= %s";
			$this->query($sql,array($tagId));
		}
	}
	/**
	 * 根据标签ID更新品牌信息
	 * @param : Array $arrSet
	 * @param : Object \haibao\cms\model\filter\Brand $filter
	 * @param : Object \haibao\cms\model\data\Brand $model
	 */
	public function updateBrandByFilter($arrSet,$filter,$model = null){

		$this->beginTranscation();
		try{
			$this->update($arrSet,$filter);
		
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		
		if( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD) ){
			//$oldId = $this->updateOldBrandLibrary($model);
		}
	}
	/**
	 * 创建老设计师空间
	 */
	private function createOldDesignerSpace(){
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
	
		$sql = "insert into  `library_brand` (`tag_id` ,`name_ch` ,`name_en` ,`date`,`tag_type`) (
		select A.tag_id ,A.tag_name,A.tag_name,%s,A.tag_type
		from tag as A
		where A.parent_id = %s and A.tag_type=%s and A.tag_id not in
		(
		select tag_id from library_brand
		)
		)";
		$this->query($sql,array(new \DateTime(),\haibao\cms\model\data\Tag::DESINGER_TAG_ID,\haibao\cms\model\data\Tag::TYPE_DESIGNER));
		return $this->getDb()->insert_id;
	}
	/**
	 * 添加老品牌数据
	 */
	private function addOldBrandLibrary($model){
		$avatar = '';
		if($model->ImgId){
			$imageData = new \haibao\cms\data\ImageLibrary();
			$avatar = $imageData->getImageUrl($model->ImgId);
			$avatar = ltrim($avatar, '/');
		}
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$brandTime = '0000-00-00';
		if($model->BrandCreateTime){
			$brandTime = $model->BrandCreateTime;
		}
		$place = 0;
		if(!empty($model->BrandRegion)){
			$place = (int)$model->BrandRegion;
		}
		$sql = "INSERT INTO `library_brand` (`tag_id`, `desc`,`avatar` ,`name_ch`,`name_en`,`pdtypes`,`place`,
											`pinyin_ch`,`pinyin_en` ,`status` ,`date`,`ad_name`,`ad_url`,
											 `brand_time`, `address`, `founder`, `cur_designer`,`story`,`buy_type`,`is_hot`,
											 `is_tuijian`,`update`)
                VALUES (%s,%s,%s, %s, %s, %s, %s, %s,%s, %s, %s,%s,%s, %s, %s, %s, %s,%s,%s,%s,%s,%s)";
		$insertArr = array($model->TagId,$model->Description, $avatar, $model->NameCN, $model->NameEN, 
					$model->Btypes,$place, $model->PinyinCN, $model->PinyinEN,
					$model->Status, $model->CreateTime,$model->AdName,$model->AdUrl, $brandTime, 
					$model->BrandCreateNation, $model->Founder,$model->CurDesigner,$model->Story,$model->BuyType,
				    $model->IsHot,$model->IsRecommend,$model->UpdateTime);
		$this->query($sql,$insertArr);
		$brandId = $this->getDb()->insert_id;
		if($model->BrandType){
			$arrValues = array();
			$arrSql = array();
			$sql = "INSERT INTO `brand_pdtype` (`bid`, `pdtypeid`) values";
			foreach ($model->BrandType as $key=>$type) {
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$brandId);
				array_push($arrValues,$type);	
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
		if($model->BrandProperty){
			$arrValues = array();
			$arrSql = array();
			$sql = "insert into `brand_property`(`bid`, `property`) values";
			foreach($model->BrandProperty as $property){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$brandId);
				array_push($arrValues,$property);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
		return $brandId;
	}
	private function addDataMigrationMap($model,$oldId){
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
		
		$tableName = $model->getTableName();
		$sql = "insert into `DataMigrationMap`(`TableName`,`PrimaryKey`,`OldPrimaryKey`)values(%s,%s,%s)";
		$this->query($sql,array($tableName,$model->Id,$oldId));
	}
	/**
	 * @param int $tagId
	 */
	public function updateLastModified($tagId){
		
		$tagData = new \haibao\cms\data\Tag();
		$tagData->updateById($tagId, array(\haibao\cms\model\filter\Tag::CONDITION_FIELD_NAME_LASTMODIFIED=>time()));
	}
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function addBrandProperty($model){
		if($model->BrandProperty){
			$arrValues = array();
			$arrSql = array();
				$sql = "insert into BrandProperty(BrandId,Property) values";
				foreach($model->BrandProperty as $property){
					array_push($arrSql,'(%s,%s)');
					array_push($arrValues,$model->Id);
					array_push($arrValues,$property);
				}
				$sql .= implode(',', $arrSql);
				$this->query($sql,$arrValues);
		}
	}
	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	public function save($model){
		$this->beginTranscation();
		try{
			$arrSet = array(
					BrandFilter::CONDITION_FIELD_NAEM_ISHOT =>$model->IsHot,
					BrandFilter::CONDITION_FIELD_NAEM_ISRECOMMEND =>$model->IsRecommend,
					BrandFilter::CONDITION_FIELD_NAEM_STORY =>$model->Story,
					BrandFilter::CONDITION_FIELD_NAME_IMGID =>$model->ImgId,
					BrandFilter::CONDITION_FIELD_NAEM_UPDATE_TIME =>$model->UpdateTime,
					BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_NATION =>$model->BrandCreateNation,
					BrandFilter::CONDITION_FIELD_NAME_BRAND_CREATE_TIME =>$model->BrandCreateTime,
					BrandFilter::CONDITION_FIELD_NAME_CURDESIGNER =>$model->CurDesigner,
					BrandFilter::CONDITION_FIELD_NAME_DESCRIPTION =>$model->Description,
					BrandFilter::CONDITION_FIELD_NAME_FOUNDER =>$model->Founder,
					BrandFilter::CONDITION_FIELD_NAME_LASTEDITEBY =>$model->LastEditeBy,
					BrandFilter::CONDITION_FIELD_NAME_NAMECN =>$model->NameCN,
					BrandFilter::CONDITION_FIELD_NAME_NAMEEN =>$model->NameEN,
					BrandFilter::CONDITION_FIELD_NAEM_BTYPES =>$model->Btypes,
					BrandFilter::CONDITION_FIELD_NAME_BRANDREGION =>$model->BrandRegion,
					BrandFilter::CONDITION_FIELD_NAME_BUYTYPE =>$model->BuyType
					);
			parent::updateById($model->Id, $arrSet);
			$delSql = "delete from BrandProperty where BrandId =%s";
			$this->query($delSql,array($model->Id));
			$this->addBrandProperty($model);
			$delSql = "delete from BrandType where BrandId =%s";
			$this->query($delSql,array($model->Id));
			$this->addBrandType($model);
		}catch (\Exception $e) {
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD) ){
			$oldId = $this->updateOldBrandLibrary($model);
		}
	}
	/**
	 * 删除品牌
	 */
	public function deleteBrandById($brandId,$status = \haibao\cms\model\data\Brand::STATUS_DISABLE){
		parent::updateById($brandId,array('Status'=>$status));
		if( \haibao\classlibrary\www\Config::getConfig(\haibao\classlibrary\www\Config::SYNC_OLD) ){
			$this->deleteOldBrandLibrary($brandId,$status);
		}
	}
	
	/**
	 * @param \haibao\cms\model\data\brand $model
	 */
	private function addBrandType($model){
		if($model->BrandType){
			$arrValues = array();
			$arrSql = array();
			$sql = "insert into BrandType(BrandId,Type) values";
			foreach($model->BrandType as $type){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$model->Id);
				array_push($arrValues,$type);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
	}
	
	private function deleteOldBrandLibrary($brandId,$status){
		$oldId = $this->getDataMigration('Brand',$brandId);
		
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$sql ="update `library_brand` set status =%s where id= %s";
		$this->query($sql,array($status,$oldId));
	}
	
	/**
	 *
	 * @param string $tableName
	 * @param int $newPrimaryKey
	 */
	private function getDataMigration($tableName,$newPrimaryKey){
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and PrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$newPrimaryKey
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$oldPrimaryKey = $result->getData('OldPrimaryKey');
		}
		return $oldPrimaryKey;
	}
	private function updateOldBrandLibrary($model){
		$oldId = $this->getDataMigration('Brand',$model->Id);
		if(!$oldId){
			return;
		}
		$avatar = '';
		if($model->ImgId){
			$imageData = new \haibao\cms\data\ImageLibrary();
			$avatar = $imageData->getImageUrl($model->ImgId);
		}
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$place = 0;
		if(!empty($model->BrandRegion)){
			$place = (int)$model->BrandRegion;
		}
		$sql ="UPDATE `library_brand` SET  `tag_id` = %s,`desc` = %s, `avatar` = %s,`name_ch` = %s,`name_en` = %s,`pdtypes`=%s,`place` = %s,`pinyin_ch` = %s,`pinyin_en` = %s,`brand_time` = %s,
		      `address` = %s,`founder`= %s,`cur_designer` = %s,`story`= %s, `buy_type` = %s,`is_hot` = %s, `is_tuijian` = %s, `update` = %s WHERE `id` =%s";
		$updateArr = array($model->TagId,$model->Description, $avatar, $model->NameCN, $model->NameEN, 
				     $model->Btypes,$place, $model->PinyinCN, $model->PinyinEN,$model->BrandCreateTime , $model->BrandCreateNation, $model->Founder, $model->CurDesigner,$model->Story,$model->BuyType,$model->IsHot,$model->IsRecommend,$model->UpdateTime,$oldId);
		$this->query($sql,$updateArr);
		$delSql = "delete from `brand_pdtype` where `bid` =%s";
		$this->query($delSql,array($oldId));
		if($model->BrandType){
			$arrValues = array();
			$arrSql = array();
			$sql = "INSERT INTO `brand_pdtype` (`bid`, `pdtypeid`) values";
			foreach ($model->BrandType as $key=>$type) {
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$oldId);
				array_push($arrValues,$type);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
		$delSql = "delete from `brand_property` where `bid` =%s";
		$this->query($delSql,array($oldId));
		if($model->BrandProperty){
			$arrValues = array();
			$arrSql = array();
			$sql = "insert into `brand_property`(`bid`, `property`) values";
			foreach($model->BrandProperty as $property){
				array_push($arrSql,'(%s,%s)');
				array_push($arrValues,$oldId);
				array_push($arrValues,$property);
			}
			$sql .= implode(',', $arrSql);
			$this->query($sql,$arrValues);
		}
	}
}
